package com.wx.api.config;


import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;

/**
 * 微信支付配置初始化
 *
 * @author liaoguz
 * @date 2023/12/09
 */
@Configuration
@Getter
public class WxPayConfig {

    /**
     *
     */
    @Value("${wx.appId}")
    private String appId;
    /**
     *
     */
    @Value("${wx.appSecret}")
    private String appSecret;
    /**
     * API V3密钥
     */
    @Value("${wx.apiV3Key}")
    private String apiV3Key;
    /**
     * 签名固定字段 微信强制要求
     */
    @Value("${wx.signPackage}")
    private String signPackage;
    /**
     * 商户证书系列号
     */
    @Value("${wx.merchantSerialNumber}")
    private String merchantSerialNumber;
    /**
     * 你的商户私钥
     */
    private PrivateKey privateKey;
    /**
     * 商户号
     */
    @Value("${wx.mchid}")
    private String mchid;
    /**
     * 支付回调地址
     */
    @Value("${wxUrl.notifyUrl}")
    private String notifyUrl;
    /**
     *
     */
    @Value("${wxUrl.getOpenIdUrl}")
    private String getOpenIdUrl;

    /**
     * 获取私钥
     * @return
     */
    @PostConstruct
    public PrivateKey getPrivateKey() {
        try {
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey
                    (new FileInputStream(ResourceUtils.getFile("classpath:apiclient_key.pem")));
            // 获取路径
            ClassPathResource resource = new ClassPathResource("apiclient_key.pem");
            // 获取流
            InputStream is = resource.getInputStream();
            this.privateKey = PemUtil.loadPrivateKey(is);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return privateKey;
    }
}
